<template>
  <el-dialog v-model="props.modelValue" style="margin-top:80px;" @close="hideModal(false)" append-to-body>
    <template #header>
      <div class="text-center font-bold text-[18px]">
        {{ props.pageType === 1 ? "商品出库" : "商品入库" }}
      </div>
    </template>
    <div class="stock-product-container">
      <div class="stock-product-image">
        <my-image fit="cover" class="w-[150px] h-[150px]" :src="form.cover" />
      </div>
      <div class="stock-product-card">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="名称: ">
              <p class="">{{ form.name }}</p>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="IP: ">
              <p class="">{{ form.pIp }}</p>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="分类: ">
              <p class="">{{ form.categoryDesc }}</p>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="库存: ">
              <p class="">{{ form.stock }} 件/个</p>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="整盒价: ">
              <p class="text-[#ffa6a6]">{{ form.boxPrice }} ￥</p>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="进价: ">
              <p class="text-blue">{{ form.buyPrice }} ￥</p>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="售价: ">
              <p class="text-[#ff4d4d]">{{ form.sellPrice }} ￥</p>
            </el-form-item>
          </el-col>
          <!-- <el-col :span="6">
            <el-form-item label="指导价: ">
              <p class="text-[#ffa6a6]">{{ form.guidePrice }} ￥</p>
            </el-form-item>
          </el-col> -->
        </el-row>
      </div>
    </div>

    <p class="my-[30px] font-bold text-[17px] text-black">
      {{ props.pageType === 1 ? "出库订单：" : "入库订单：" }}
    </p>
    <el-form :model="form" class="text-black font-bold mt-[10px]" size="large" label-width="auto">
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item :label="props.pageType === 1 ? '成交价: ' : '进货价: '">
            <el-input-number v-model="order.price" :precision="2" :step="0.1" :max="1000" :min="0" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="props.pageType === 1 ? '成交数(件/个): ' : '进货数(件/个): '">
            <el-input-number v-model="order.total" :max="countStock" :min="1" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item :label="props.pageType === 1 ? '成交总额: ' : '进价总额: '">
            <el-input-number v-model="sum" :precision="2" :max="100000" :min="0" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="'邮费: '">
            <el-input-number v-model="order.postage" :precision="2" :max="10" :min="0" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item :label="props.pageType === 1 ? '出货时间: ' : '入货时间: '">
            <el-date-picker v-model="order.orderDate" type="datetime" placeholder="请选择时间" :default-time="new Date()" />
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>

    <template #footer>
      <div class="dialog-footer">
        <el-button size="large" color="#fd3838" style="color: #fff;" @click="submit">提交</el-button>
        <el-button size="large" type="primary" @click="hideModal(false)">关闭</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script lang="ts" setup>
import ProductService from "@/api/ProductService";
import { Product, Stock } from "./type";
import Decimal from 'decimal.js';

type Props = {
  modelValue: boolean;
  pageType: number; //0入库 1出库
  currentProduct: Product;
  currentStock?: Stock;
  refresh: Function;
};

type State = {
  form: Product;
  order: {
    total: number;
    price: number;
    sum: number;
    postage: number;
    orderDate: Date;
  };
}

const props = withDefaults(defineProps<Props>(), {});

const state = reactive<State>({
  form: {} as Product,
  order: {
    total: 1,
    price: 0,
    sum: 0,
    postage: 0,
    orderDate: new Date(),
  },
});

const { form, order } = toRefs(state);

const sum = computed(() => {
  const { price, total } = order.value
  if (order.value.price && order.value.total) {
    const result = new Decimal(price).mul(total).toNumber()
    return (state.order.sum = result);
  }
  return 0;
});

const countStock = computed((): number => {
  const { form } = state
  if (props.currentStock?.guid) {
    return parseInt(props.currentStock?.total) + props.currentProduct.stock
  }
  return props.pageType === 1 ? form.stock : 10000
})

const emit = defineEmits([
  "update:modelValue",
  "update:pageType",
  "update:currentProduct",
]);

const refresh = () => {
  props.refresh?.();
};

const hideModal = (bool: boolean) => {
  emit("update:modelValue", false);
  emit("update:pageType", 0);
  emit("update:currentProduct", {});
  bool && refresh();
};

const init = () => {
  state.form = props.currentProduct as any;
  state.order.price = new Decimal(props.currentProduct.sellPrice).toNumber();
  if (props.currentStock?.pId) {
    const { price, total, orderDate } = props.currentStock
    state.order.price = new Decimal(price).toNumber();
    state.order.total = parseInt(total)
    state.order.orderDate = orderDate
  }
};

const submit = () => {
  if (props.currentStock?.pId) {
    // 编辑出入库
    return updateStockRecord();
  }
  if (props.pageType === 0) {
    // 入库 0
    return saveStockRecord(0);
  }
  if (props.pageType === 1) {
    // 出库 1
    return saveStockRecord(1);
  }
};

const saveStockRecord = async (type: number) => {
  const { form, order } = state;
  if (type == 1) {
    if (form.stock < order.total) {
      return Utils.Modal().alertWarning('超过最大库存~');
    }
  }
  const params = {
    type,
    pId: form.pId,
    price: order.price,
    total: order.total,
    sum: order.sum,
    postage: order.postage,
    orderDate: order.orderDate,
  };
  const [err, res] = await ProductService.saveStockRecord(params);
  if (err) {
    return Utils.Modal().msgError(err);
  }
  Utils.Modal().msgSuccess(type === 1 ? "出库成功~" : "入库成功~");
  return hideModal(true);
};

const updateStockRecord = async () => {
  const { pageType: type, currentStock } = props
  const { form, order } = state;
  const params = {
    guid: currentStock?.guid,
    pId: form.pId,
    price: order.price,
    total: order.total,
    sum: order.sum,
    postage: order.postage,
    orderDate: order.orderDate,
  };
  const [err, res] = await ProductService.updateStockRecord(params);
  if (err) {
    return Utils.Modal().msgError(err);
  }
  Utils.Modal().msgSuccess(type === 1 ? "修改出库成功~" : "修改入库成功~");
  return hideModal(true);
}

init();
</script>

<style lang="scss" scoped>
.stock-product-container {
  background-color: #FFE53B;
  background-image: linear-gradient(147deg, #FFE53B 0%, #fd3838 74%);
  position: relative;
  padding: 70px 0;
}

.stock-product-card {
  color: #000;
  font-weight: bolder;
  display: flex;
  flex-flow: column;
  justify-content: space-evenly;
  width: 600px;
  height: 200px;
  border-radius: 20px;
  padding: 20px 10px 0px 80px;
  background-color: #fff;
  box-shadow: 0px 0px 20px rgba(252, 56, 56, 0.3);
  margin-left: 200px;
}

.stock-product-image {
  position: absolute;
  top: 95px;
  left: 190px;
  width: 150px;
  flex-shrink: 0;
  height: 150px;
  background-image: linear-gradient(147deg, #fe8a39 0%, #fd3838 74%);
  box-shadow: 4px 13px 30px 1px rgba(252, 56, 56, 0.2);
  border-radius: 20px;
  transform: translateX(-80px);
  overflow: hidden;
}
</style>
